package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.common.constant.Constants;
import cn.itsource.ymcc.common.constant.RConst;
import cn.itsource.ymcc.common.constant.TaskConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.dto.PreOrderDto;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(consumerGroup = "Kill_order_consumer",
        //Topic
        topic = TaskConstants.TOPIC_ORDER_TIMEOUT,
        //TAGS
        selectorExpression = TaskConstants.TAGS_ORDER_TIMEOUT
)
public class KillOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String orderNo = new String(body, Constants.UTF8);
            CourseOrder one = courseOrderService.getOne(new LambdaQueryWrapper<CourseOrder>().eq(CourseOrder::getOrderNo, orderNo));
            if(one.getStatusOrder()== RConst.Num.INT_0 || one.getStatusOrder()==RConst.Num.INT_4){
                //删除购买资格
                PreOrderDto preOrderDto  =(PreOrderDto)redisTemplate.opsForValue().get(TaskConstants.KEY_PREFIX_PRE_ORDER + ":" + orderNo);
                redisTemplate.delete(TaskConstants.KEY_PREFIX_PRE_ORDER + ":" + orderNo);
                //还原
                Integer count = preOrderDto.getCount();
                Long killCourseId = preOrderDto.getKillCourseId();
                Integer o = (Integer)redisTemplate.opsForValue().get(TaskConstants.KILL_STORE + ":" + killCourseId);
                redisTemplate.opsForValue().set(TaskConstants.KILL_STORE + ":" + killCourseId,count+o);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
